//
//  TBRGetPlaneMessageC.m
//  TBRentClient
//
//  Created by tonbright on 2018/5/15.
//  Copyright © 2018年 tonbright. All rights reserved.
//

#import "TBRGetPlaneMessageC.h"
#import "TBRMineVipIconCell.h"
#import "TBRMineVipDetailCell.h"
#import "TBRMineModel.h"
#import <YYModel.h>
#import "NetWorkRequest.h"
#import <IQKeyboardManager.h>
#import "YXDateHelpObject.h"
#import "TBRRecevePlaneTimePickerC.h"

#import "TBRRecevePlaneMessagePickerC.h"

@interface TBRGetPlaneMessageC ()
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,copy)NSString *selDateStr;
@property (nonatomic,copy)NSString *selAutualDateStr;

@property (weak, nonatomic) IBOutlet UIView *view_planeNum;

@property (weak, nonatomic) IBOutlet UIView *view_dateTime;

@property (weak, nonatomic) IBOutlet UITextField *tf_planeNum;

@property (weak, nonatomic) IBOutlet UILabel *lbe_time;

@end

@implementation TBRGetPlaneMessageC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    
    //加载数据
    [self loadData];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_tf_planeNum addDoneOnKeyboardWithTarget:self action:@selector(doneBtnClick)];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [_tf_planeNum becomeFirstResponder];
//    [_tf_planeNum addPreviousNextDoneOnKeyboardWithTarget:self previousAction:nil nextAction:nil doneAction:@selector(doneBtnClick)];
    [_tf_planeNum addDoneOnKeyboardWithTarget:self action:@selector(doneBtnClick)];
}

- (void)doneBtnClick {
    _view_dateTime.hidden = NO;
    [[IQKeyboardManager sharedManager] resignFirstResponder];
//    [_tf_planeNum resignFirstResponder];
    
    //添加时间选择器----------------
    [self alert];
}


- (IBAction)selDateBtnClick:(UIButton *)sender {
    [self.view endEditing:YES];
    [self alert];
}


- (void)alert {
    __weak typeof(self) weakSelf = self;
    TBRRecevePlaneTimePickerC *pickerC = [[TBRRecevePlaneTimePickerC alloc] init];
    __weak TBRRecevePlaneTimePickerC *weakPickerC = pickerC;
    pickerC.pickerViewCancleBtnBlock = ^{
        [weakPickerC removeFromParentViewController];
        [weakPickerC.view removeFromSuperview];
    };

    pickerC.pickerViewSureBtnBlock = ^(NSString *dateStr,NSString *yeadMonthStr,NSInteger index) {
        NSArray *tmpArray = @[@"昨天",@"今天",@"明天",@"后天"];
        NSString *tmpStr = tmpArray[index];
        [weakPickerC removeFromParentViewController];
        [weakPickerC.view removeFromSuperview];
        NSString *tmpSelStr = [NSString stringWithFormat:@"%@ %@",tmpStr,dateStr];
        weakSelf.lbe_time.text = tmpSelStr;

        weakSelf.selDateStr = dateStr;
        weakSelf.selAutualDateStr = yeadMonthStr;
        //判断航班号和时间都存在的话就回调---
        [weakSelf loadNetData];
//        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    [self.navigationController addChildViewController:pickerC];
    [self.navigationController.view addSubview:pickerC.view];
    pickerC.view.frame = [UIApplication sharedApplication].keyWindow.frame;
    pickerC.view.frame = CGRectMake(0, 0, Width, Height + 49);
}

- (void)setupUI {
    //设置导航条
    [self setupNavItem];
}

- (void)setupNavItem {
    self.titleText = @"航班查询";
}



// MARK: - 加载数据
- (void)loadData {
    [self loadLocalData];
//    [self loadNetData];
}
// MARK: - 本地数据
- (void)loadLocalData {
//    NSString *currentDateStr = [[YXDateHelpObject manager] getCurentTime:@"M月dd日" dateN:[NSDate date]];
    _lbe_time.text = [NSString stringWithFormat:@"请选择当地起飞时间"];
}

// MARK: - 获取网络数据-----
- (void)loadNetData {
    NSDictionary *dic = @{@"key":mobAppKey,@"name":[HelpObject changeNull:_tf_planeNum.text]};
    [self progressHUDShowWithText:@"加载中..."];
    __weak typeof(self) weakSelf = self;
//实时的    http://op.juhe.cn/flight/df/hfs       http://op.juhe.cn/flight/ff
    [NetWorkRequest getOriginUrl:@"http://apicloud.mob.com/flight/no/query" parmeters:dic response:^(NSDictionary *response) {
        if (!response) {
//            weakSelf.lbe_time.text = [NSString stringWithFormat:@"请选择当地起飞时间"];
            return;
        }
        [weakSelf progressHUDHideImmediately];
        NSArray *resultArray = [NSArray yy_modelArrayWithClass:[TBRGetPlaneMessageModel class] json:response[@"result"]];
        if (resultArray.count > 1) {
            //弹出选择框
            TBRRecevePlaneMessagePickerC *planeMessagePickerC = [[TBRRecevePlaneMessagePickerC alloc] init];
            planeMessagePickerC.dateArray = resultArray;
            __weak TBRRecevePlaneMessagePickerC *weakPickerC = planeMessagePickerC;
            planeMessagePickerC.pickerViewCancleBtnBlock = ^{
                [weakPickerC removeFromParentViewController];
                [weakPickerC.view removeFromSuperview];
            };
            planeMessagePickerC.pickerViewSureBtnBlock = ^(TBRGetPlaneMessageModel *selModel) {
                [weakPickerC removeFromParentViewController];
                [weakPickerC.view removeFromSuperview];
                
                //如果选择昨天的话-----到达时间可能是昨天或者今天上午
                BOOL isHeFa = [weakSelf judgePlaneIsOutModel:selModel];
                if (isHeFa == NO) {
                    return;
                }
                if (weakSelf.getPlaneMessageCBlock) {
                    weakSelf.getPlaneMessageCBlock(selModel);
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }
            };
            [self.navigationController addChildViewController:planeMessagePickerC];
            [self.navigationController.view addSubview:planeMessagePickerC.view];
            planeMessagePickerC.view.frame = CGRectMake(0, 0, Width, Height + 49);

        }else if (resultArray.count == 1) {
            //默认选中当前信息并回退到上个页面
            //判断飞机是否降落---------
            TBRGetPlaneMessageModel *selModel = resultArray.firstObject;
            BOOL isHeFa = [weakSelf judgePlaneIsOutModel:selModel];
            if (isHeFa == NO) {
                return;
            }
            if (weakSelf.getPlaneMessageCBlock) {
                weakSelf.getPlaneMessageCBlock(selModel);
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        }else {
            //给出提示未找到指定的航班信息
            [weakSelf setNoticeText:@"未找到指定的航班信息"];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDHideImmediately];
    }];
}


// MARK: - 判断航班是否过期--------
- (BOOL)judgePlaneIsOutModel:(TBRGetPlaneMessageModel *)selModel {
    selModel.selDateStr = self.selDateStr;
    selModel.selAutualDateStr = self.selAutualDateStr;
    //选择目的地未开通服务
    if (![selModel.toCityName isEqualToString:@"上海"]) {
        [self setNoticeText:@"用车城市暂未开通接机服务"];
        return NO;
    }
    
    //到达时间
    //09:35   5月20号
    //如果选择的是今天的话-----到达时间可能是今天  或者明天的早上
    NSString *startDateStr = [NSString stringWithFormat:@"%@ %@",selModel.selAutualDateStr,selModel.planTime];// selModel.planTime;
    NSDate *startDate = [[YXDateHelpObject manager] getDataFromStrFormat:@"yyyy/M/d HH:mm" String:startDateStr];
    
    //往后推几个小时
    NSInteger durationH = [[selModel.flightTime componentsSeparatedByString:@"h"].firstObject integerValue];
    //往后推几分-------取出到达的时间------
    NSString *tmpMinStr = [selModel.flightTime componentsSeparatedByString:@"h"].lastObject;
    NSInteger durationMin = [[tmpMinStr componentsSeparatedByString:@"m"].firstObject integerValue];
    
    NSDate *arriveDateJiSuan = [[YXDateHelpObject manager] getEarlyOrLaterDate:startDate LeadTime:durationH Type:3];//计算出来的道道时间
    arriveDateJiSuan = [[YXDateHelpObject manager] getEarlyOrLaterDate:arriveDateJiSuan LeadTime:durationMin Type:4];//计算出来的道道时间
    NSString *arriveDateJiSuanStr = [[YXDateHelpObject manager] getStrFromDateFormat:@"yyyy/M/dd" Date:arriveDateJiSuan];
    NSString *arriveDateJiSuanStrFinal = [NSString stringWithFormat:@"%@ %@",arriveDateJiSuanStr,selModel.planArriveTime];// selModel.planTime;
    NSDate *arriveDateJiSuanDateFinal = [[YXDateHelpObject manager] getDataFromStrFormat:@"yyyy/M/dd H:mm" String:arriveDateJiSuanStrFinal];
    
    NSString *arriveDateJiSuanStrFinalYueRi = [[YXDateHelpObject manager] getStrFromDateFormat:@"M月dd日" Date:arriveDateJiSuanDateFinal];
    selModel.showselDateStr = arriveDateJiSuanStrFinalYueRi;
    selModel.showselAutualDateStr = arriveDateJiSuanStrFinal;
    
//    NSDate *tmpArriveDateJiSuan = [[YXDateHelpObject manager] getEarlyOrLaterDate:arriveDateJiSuanDateFinal LeadTime:2 Type:3];//计算出来的道道时间
    NSDate *currentDate = [NSDate date];
    NSDate *tmpCurrentDate = [[YXDateHelpObject manager] getEarlyOrLaterDate:currentDate LeadTime:2 Type:3];
    if ([arriveDateJiSuanDateFinal timeIntervalSinceDate:tmpCurrentDate] <= 0) {
        [self setNoticeText:@"航班已降落或超出预约用车时间"];
        return NO;
    }
    return YES;
    
    
}

@end
